<template>
  <div class="login-form-wrapper">
    <div class="login-form-title">Hello, Example</div>
    <a-card hoverable>
      <div
        :style="{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        alignItems: 'center',
        height: '50px'
      }"
      >
      <span
        :style="{ display: 'flex', alignItems: 'center', color: '#1D2129' }"
      >
        <a-image
          width="75"
          :src="currentTenant.logo"
          style="margin-right: 10px"
        />
        <a-typography-text bold>{{ currentTenant.name }}</a-typography-text>
      </span>
        <a-link @click="onSwitch">切换租户</a-link>
      </div>
    </a-card>
    <div class="login-form-error-msg">{{ errorMessage }}</div>
    <a-form
      ref="loginForm"
      :model="userInfo"
      class="login-form"
      layout="vertical"
      @submit="handleSubmit"
    >
      <a-form-item
        field="username"
        :rules="[{ required: true, message: '用户名不能为空' }]"
        :validate-trigger="['change', 'blur']"
        hide-label
      >
        <a-input
          v-model="userInfo.username"
          placeholder="用户名：admin"
        >
          <template #prefix>
            <icon-user />
          </template>
        </a-input>
      </a-form-item>
      <a-form-item
        field="password"
        :rules="[{ required: true, message: '密码不能为空' }]"
        :validate-trigger="['change', 'blur']"
        hide-label
      >
        <a-input-password
          v-model="userInfo.password"
          placeholder="密码：admin"
          allow-clear
        >
          <template #prefix>
            <icon-lock />
          </template>
        </a-input-password>
      </a-form-item>
      <a-space :size="16" direction="vertical">
        <div class="login-form-password-actions">
          <a-link>忘记密码</a-link>
        </div>
        <a-button type="primary" html-type="submit" long :loading="loading">
          登录
        </a-button>
        <a-button type="text" long class="login-form-register-btn">
          注册账号
        </a-button>
      </a-space>
    </a-form>
    <a-modal v-model:visible="visible" width="700px" @ok="switchTenant">
      <template #title>
        切换租户
      </template>
      <div>
        <a-radio-group v-model:model-value="selectTenantId">
          <template v-for="(tenant, index) in tenants" :key="index">
            <a-radio :value="tenant.tenantId">
              <template #radio="{ checked }">
                <a-space
                  align="start"
                  class="custom-radio-card"
                  :class="{ 'custom-radio-card-checked': checked }"
                >
                  <div style="align-items: center; display: flex; cursor: pointer; height: 70px">
                    <a-image
                      width="75"
                      :src="tenant.logo"
                      :preview="false"
                    />
                    <div class="custom-radio-card-title">
                      {{ tenant.name }}
                    </div>
                  </div>
                </a-space>
              </template>
            </a-radio>
          </template>
        </a-radio-group>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onBeforeMount } from "vue";
import { useRouter } from "vue-router";
import { Message } from "@arco-design/web-vue";
import { ValidatedError } from "@arco-design/web-vue/es/form/interface";
import { useAppStore, useTabBarStore, useUserStore } from "@/store";
import { DEFAULT_ROUTE_NAME } from "@/router/constants";
import useLoading from "@/hooks/loading";
import { list } from "@/api/modules/system/tenant";
import { buildVueRouter } from "@/utils/menu";
import type { LoginData } from "@/types/modules/auth";
import type { TenantVo } from "@/types/modules/system";
import { getTenant, setTenant } from "@/utils/tenant";

const currentTenant = ref<TenantVo>({});
const selectTenantId = ref<string>();
const visible = ref<boolean>(false);
const tenants = ref<TenantVo[]>([]);
const router = useRouter();
const errorMessage = ref<string>("");
const { loading, setLoading } = useLoading();
const userStore = useUserStore();

const onSwitch = async () => {
  if (!tenants.value.length) {
    tenants.value = (await list()).data;
  }
  selectTenantId.value = currentTenant.value.tenantId
  visible.value = true;
};

const switchTenant = () => {
  tenants.value.forEach((tenant) => {
    if (tenant.tenantId === selectTenantId.value) {
      setTenant(tenant);
      currentTenant.value = getTenant();
    }
  });

};


const userInfo = reactive({
  username: 'admin',
  password: 'admin'
});

const handleSubmit = async ({ errors, values }: {
  errors: Record<string, ValidatedError> | undefined;
  values: Record<string, any>;
}) => {
  if (!errors) {
    setLoading(true);
    try {
      await userStore.login(values as LoginData);
      const appStore = useAppStore();
      await appStore.fetchServerMenuConfig();
      // @ts-ignore
      buildVueRouter(appStore.appAsyncMenus).forEach(router.addRoute);
      await router.push({
        name: DEFAULT_ROUTE_NAME
      });
      Message.success("欢迎使用");
    } catch (err) {
      errorMessage.value = (err as Error).message;
    } finally {
      setLoading(false);
    }
  }
};

onBeforeMount(() => {
  currentTenant.value = getTenant() || { tenantId: "", name: "" };
  const tabBarStore = useTabBarStore();
  tabBarStore.$reset();
});
</script>

<style lang="less" scoped>
.login-form {
  &-wrapper {
    width: 320px;
  }

  &-title {
    color: var(--color-text-1);
    font-weight: 500;
    font-size: 24px;
    line-height: 32px;
  }

  &-sub-title {
    color: var(--color-text-3);
    font-size: 16px;
    line-height: 24px;
  }

  &-error-msg {
    height: 32px;
    color: rgb(var(--red-6));
    line-height: 32px;
  }

  &-password-actions {
    display: flex;
    justify-content: space-between;
  }

  &-register-btn {
    color: var(--color-text-3) !important;
  }
}

.custom-radio-card {
  padding: 10px 16px;
  border: 1px solid var(--color-border-2);
  border-radius: 4px;
  width: 100%;
  box-sizing: border-box;
  margin-right: 5px;
}

.custom-radio-card-mask {
  height: 14px;
  width: 14px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border-radius: 100%;
  border: 1px solid var(--color-border-2);
  box-sizing: border-box;
}

.custom-radio-card-mask-dot {
  width: 8px;
  height: 8px;
  border-radius: 100%;
}

.custom-radio-card-title {
  color: var(--color-text-1);
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 8px;
  padding-left: 10px;
}

.custom-radio-card:hover,
.custom-radio-card-checked,
.custom-radio-card:hover .custom-radio-card-mask,
.custom-radio-card-checked .custom-radio-card-mask {
  border-color: rgb(var(--primary-6));
}

.custom-radio-card-checked {
  background-color: var(--color-primary-light-1);
}

.custom-radio-card:hover .custom-radio-card-title,
.custom-radio-card-checked .custom-radio-card-title {
  color: rgb(var(--primary-6));
}

.custom-radio-card-checked .custom-radio-card-mask-dot {
  background-color: rgb(var(--primary-6));
}
</style>
